<?php
/**
+-----------------------------------------------------------------------------------------------
* GouGuOPEN [ 左手研发，右手开源，未来可期！]
+-----------------------------------------------------------------------------------------------
* @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
+-----------------------------------------------------------------------------------------------
* @Licensed 勾股OA，开源且可免费使用，但并不是自由软件，未经授权许可不能去除勾股OA的相关版权信息
+-----------------------------------------------------------------------------------------------
* @Author勾股工作室 <hdm58@qq.com>
+-----------------------------------------------------------------------------------------------
*/
namespace app\lawcase\model;

use think\Model;
use think\facade\Db;

class CaseParty extends Model
{
    // 设置当前模型对应的数据表名称
    protected $name = 'case_party';
    
    // 设置数据表前缀
    protected $prefix = 'oa_';
    
    // 设置主键
    protected $pk = 'id';
    
    // 设置自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 获取案件当事人列表
     * @param array $where 查询条件
     * @param array $param 分页参数
     * @return array
     */
    public function getList($where = [], $param = [])
    {
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $order = empty($param['order']) ? 'id desc' : $param['order'];
        try {
            $list = $this->where($where)
                ->where('delete_time', 0)
                ->order($order)
                ->paginate(['list_rows' => $rows, 'query' => $param])
                ->each(function($item) {
                    // 获取案件信息
                    $case = Db::name('lawcase')->where('id', $item->case_id)->find();
                    $item->case_name = $case ? $case['name'] : '';
                    $item->case_no = $case ? $case['case_no'] : '';

                    // 获取当事人信息
                    $party = Db::name('party')->where('id', $item->party_id)->find();
                    $item->party_name = $party ? $party['name'] : '';
                    $item->party_type = $party ? $party['type'] : '';

                    // 格式化角色类型和诉讼地位
                    $item->role_type_text = $this->getRoleTypeText($item->role_type);
                    $item->party_type_text = $this->getPartyTypeText($item->party_type);

                    return $item;
                });
            return $list;
        } catch (\Exception $e) {
            return ['code' => 1, 'data' => [], 'msg' => $e->getMessage()];
        }
    }

    /**
     * 添加案件当事人关联
     * @param array $data 关联数据
     * @return int|string新增ID
     */
    public function add($data)
    {
        try {
            $data['create_time'] = time();
            $id = $this->strict(false)->insertGetId($data);
            add_log('add', $id, $data);
            return $id;
        } catch (\Exception $e) {
            throw new \Exception('添加案件当事人关联失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑案件当事人关联
     * @param array $data 关联数据
     * @return bool
     */
    public function edit($data)
    {
        try {
            $data['update_time'] = time();
            $res = $this->strict(false)->where('id', $data['id'])->update($data);
            add_log('edit', $data['id'], $data);
            return $res !== false;
        } catch (\Exception $e) {
            throw new \Exception('编辑案件当事人关联失败：' . $e->getMessage());
        }
    }

    /**
     * 删除案件当事人关联
     * @param int|array $ids 关联ID或ID数组
     * @return bool
     */
    public function remove($ids)
    {
        try {
            $ids = is_array($ids) ? $ids : [$ids];
            $this->where('id', 'in', $ids)->update(['delete_time' => time()]);
            foreach ($ids as $id) {
                add_log('delete', $id);
            }
            return true;
        } catch (\Exception $e) {
            throw new \Exception('删除案件当事人关联失败：' . $e->getMessage());
        }
    }

    /**
     * 获取案件当事人关联详情
     * @param int $id 关联ID
     * @return array|null
     */
    public function getDetail($id)
    {
        $detail = $this->where(['id' => $id, 'delete_time' => 0])->find();
        if (!$detail) {
            return null;
        }

        $detail = $detail->toArray();

        // 获取案件信息
        $case = Db::name('lawcase')->where('id', $detail['case_id'])->find();
        $detail['case_name'] = $case ? $case['name'] : '';
        $detail['case_no'] = $case ? $case['case_no'] : '';

        // 获取当事人信息
        $party = Db::name('party')->where('id', $detail['party_id'])->find();
        $detail['party_name'] = $party ? $party['name'] : '';
        $detail['party_type'] = $party ? $party['type'] : '';

        // 格式化角色类型和诉讼地位
        $detail['role_type_text'] = $this->getRoleTypeText($detail['role_type']);
        $detail['party_type_text'] = $this->getPartyTypeText($detail['party_type']);

        return $detail;
    }

    /**
     * 批量添加案件当事人关联
     * @param int $caseId 案件ID
     * @param array $parties 当事人数据[['party_id' => 1, 'role_type' => 1, 'party_type' => 1], ...]
     * @return array添加结果，包含成功数量和失败数量
     */
    public function batchAdd($caseId, $parties)
    {
        $success = 0;
        $fail = 0;
        $time = time();Db::startTrans();
        try {
            foreach ($parties as $party) {
                $data = [
                    'case_id' => $caseId,
                    'party_id' => $party['party_id'],
                    'role_type' => $party['role_type'],
                    'party_type' => $party['party_type'],
                    'create_time' => $time
                ];
                $id = $this->strict(false)->insertGetId($data);
                if ($id) {
                    $success++;
                add_log('add', $id, $data);
                } else {
                    $fail++;
                }
            }
            Db::commit();
            return ['success' => $success, 'fail' => $fail];
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('批量添加案件当事人关联失败：' . $e->getMessage());
        }
    }

    /**
     * 获取案件的所有当事人
     * @param int $caseId 案件ID
     * @return array
     */
    public function getCaseParties($caseId)
    {
        return $this->alias('cp')
            ->join('party p', 'cp.party_id = p.id')
            ->where(['cp.case_id' => $caseId, 'cp.delete_time' => 0])
            ->field('cp.*, p.name as party_name, p.type as party_type, p.id_number, p.phone')
            ->select()
            ->each(function($item) {
                $item['role_type_text'] = $this->getRoleTypeText($item['role_type']);
                $item['party_type_text'] = $this->getPartyTypeText($item['party_type']);return $item;
            })
            ->toArray();
    }

    /**
     * 获取当事人角色类型文本
     * @param int $roleType 角色类型值
     * @return string
     */
    protected function getRoleTypeText($roleType)
    {
        $types = [
            1 => '委托人',
            2 => '对方当事人',
            3 => '第三人'
        ];
        return isset($types[$roleType]) ? $types[$roleType] : '未知角色';
    }

    /**
     * 获取诉讼地位文本
     * @param int $partyType 诉讼地位值
     * @return string
     */
    protected function getPartyTypeText($partyType)
    {
        $types = [
            1 => '原告',
            2 => '被告',
            3 => '上诉人',
            4 => '被上诉人',
            5 => '申请人',
            6 => '被申请人'
        ];
        return isset($types[$partyType]) ? $types[$partyType] : '未知地位';
    }
}